package com.briup.corejava.day21;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 具有功能的服务器
 * 1、反转信息
 * 2、增加多线程
 */
public class TcpServerPlus {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        int port = 8888;
        // 准备增强流

        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务器开启监听...");
            while (true) {
                Socket socket = serverSocket.accept();
                // 多线程拓展，每监听到一个socket，开启一个子线程处理
                Thread t = new Thread() {
                    @Override
                    public void run() {
                        BufferedReader br = null;
                        PrintWriter pw = null;
                        try {
                            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            pw = new PrintWriter(socket.getOutputStream());

                            // 准备StringBuffer来拼接字符串
                            StringBuffer sb = new StringBuffer();
                            while (true) {
                                // 每次进来进行清空
                                sb.delete(0, sb.length());
                                String line = br.readLine();
                                System.out.println("服务器端收到的数据：" + line);
                                if ("quit".equals(line)) break;
                                // 保存数据
                                sb.append(line);
                                // 反转数据
                                sb.reverse();
                                // 写回到客户端
                                pw.println(sb.toString());
                                pw.flush();
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }finally {
                            // 关闭资源
                        }
                    }
                };
                t.start();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
